﻿using Consul;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Text;
using Volo.Abp.DependencyInjection;

namespace Ebusiness_OrderService.Register
{
    /// <summary>
    /// 
    /// </summary>
    [Dependency(ServiceLifetime.Singleton)]
    public class RegisterCenterServiceRegister
    {
        public ServiceRegisteryOption serviceRegisteryOption { get; set; }
        public RegisterCenterServiceRegister(IOptions<ServiceRegisteryOption> options)
        {
            serviceRegisteryOption = options.Value;
        }

        //public static string GetLocalIPAddress()
        //{
        //    var host = Dns.GetHostEntry(Dns.GetHostName());
        //    return host.AddressList.First(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
        //}

        /// <summary>
        /// 注册服务
        /// </summary>
        public async void Register()
        {
            //var ip = GetLocalIPAddress();
            //Consul服务器地址
            using (var consulClient = new ConsulClient(cfg => { cfg.Address = new Uri(serviceRegisteryOption.ConsulClientAddress); }))
            {
                //创建服务地址
                var url = new Uri(serviceRegisteryOption.ServiceAddress);
                //注册服务地址
                var registeration = new AgentServiceRegistration()
                {
                    ID = serviceRegisteryOption.ServiceId, //唯一标识符

                    Name = serviceRegisteryOption.ServiceName,   //名称
                    Address = url.Host,  //地址
                    Port = url.Port,  //端口
                    Tags = new string[] { },   //标签  
                    Check = new AgentServiceCheck() // 健康检测  http://192.168.3.51:44337/health
                    {
                        //consul检测超时时间
                        Timeout = TimeSpan.FromSeconds(10),
                        TLSSkipVerify = true,
                        //服务停止5秒后注销服务
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10),
                        //consul健康检测地址
                        HTTP = serviceRegisteryOption.ServiceHealthAddress,
                        //consul健康检查间隔时间
                        Interval = TimeSpan.FromSeconds(10)
                    }
                };
                //var putPair = new KVPair("config/app1/db")
                //{
                //    Value = Encoding.UTF8.GetBytes("mysql")
                //};

                //consulClient.KV.Put(putPair).Wait();
                //Console.WriteLine("添加成功");

                var result = await consulClient.KV.Get("config/app1/db");
                if (result.Response != null)
                {
                    var value = Encoding.UTF8.GetString(result.Response.Value);
                    Console.WriteLine($"读取成功，值为: {value}");
                }
                else
                {
                    Console.WriteLine("Key 不存在");
                }

                consulClient.Agent.ServiceRegister(registeration).Wait();
                Console.WriteLine($"订单微服务注册成功：{serviceRegisteryOption.ServiceAddress}");
            }
        }

        /// <summary>
        /// 删除服务
        /// </summary>
        public void DeleteRegister()
        {
            //Consul服务器地址
            using (var consulClient = new ConsulClient(cfg => { cfg.Address = new Uri(serviceRegisteryOption.ConsulClientAddress); }))
            {
                //创建服务地址
                //var url = new Uri("http://127.0.0.1:44337");
                //服务删除
                consulClient.Agent.ServiceDeregister(serviceRegisteryOption.ServiceId).Wait();
                //服务删除成功
                Console.WriteLine($"订单微服务删除成功：{serviceRegisteryOption.ServiceAddress}");
            }
        }
    }
}
